package me.flyray.crm.core.biz.personal;

import me.flyray.common.enums.CustomerType;
import me.flyray.common.enums.MerchantType;
import me.flyray.common.enums.PointsTradeType;
import me.flyray.common.enums.TradeType;
import me.flyray.common.msg.AccountType;
import me.flyray.common.msg.BaseApiResponse;
import me.flyray.common.msg.ResponseCode;
import me.flyray.common.util.SnowFlake;
import me.flyray.common.vo.*;
import me.flyray.common.vo.admin.AdminUserRequest;
import me.flyray.common.vo.admin.AdminUserResponse;
import me.flyray.crm.core.biz.customer.CustomerBaseBiz;
import me.flyray.crm.core.biz.customer.CustomerIntoAccountBiz;
import me.flyray.crm.core.entity.*;
import me.flyray.crm.core.mapper.*;
import me.flyray.crm.core.util.PageResult;
import me.flyray.crm.facade.feignclient.modules.admin.AdminUserServiceClient;
import me.flyray.crm.facade.request.IntoAccountRequest;
import me.flyray.crm.facade.request.PersonalBaseAddRequest;
import me.flyray.crm.facade.request.PersonalBaseModifyRequest;
import me.flyray.crm.facade.request.WechatUnBindRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import me.flyray.common.biz.BaseBiz;
import org.springframework.util.CollectionUtils;
import sun.font.TrueTypeFont;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 个人基础信息扩展表
 * @email ${email}
 * @date 2018-08-14 14:15:09
 */
@Service
public class PersonalBaseExtBiz {

    @Resource
    private PersonalBaseExtMapper personalBaseExtMapper;
    @Resource
    private PersonalBaseMapper personalBaseMapper;
    @Resource
    private PersonalDistributionRelationMapper personalDistributionRelationMapper;
    @Resource
    private AdminUserServiceClient adminUserServiceClient;
    @Resource
    private CustomerBaseAuthMapper customerBaseAuthMapper;
    @Resource
    private PersonalAccountBiz personalAccountBiz;
    @Resource
    private CustomerIntoAccountBiz customerIntoAccountBiz;
    @Resource
    private CustomerBaseMapper customerBaseMapper;

    public List<QueryPersonalInfoExtResponse> queryWithPointsList(QueryPersonalBaseExtRequest request, PageResult pageResult) {
        Integer pageSize = request.getPageSize();
        Integer currentPage = request.getCurrentPage();
        if(pageSize == null || pageSize.intValue() == 0){
            pageSize = 10;
        }
        if(currentPage == null || currentPage.intValue() == 0){
            currentPage = 1;
        }
        Integer startRow = (currentPage -1) * pageSize;
        if(! "1".equals(request.getUserType())){
            request.setOwnerId(request.getUserId());
        }
        Integer count  = personalBaseExtMapper.getPageCount(request.getPersonalId(), request.getRealName(), request.getMobile(),
                request.getAuthenticationStatus(), request.getOwnerId(), request.getPersonalLevel(), request.getPlatformId());
        List<PersonalBase> personalBaseExtList = personalBaseExtMapper.getPageInfos(request.getPersonalId(), request.getRealName(), request.getMobile(),
                request.getAuthenticationStatus(), request.getOwnerId(), request.getPersonalLevel(),request.getPlatformId(), startRow, pageSize);
        List<QueryPersonalInfoExtResponse> queryPersonalInfoExtResponseList = new ArrayList<QueryPersonalInfoExtResponse>();
        if(!CollectionUtils.isEmpty(personalBaseExtList)){
            for (PersonalBase personalBase :personalBaseExtList) {
                QueryPersonalInfoExtResponse queryPersonalInfoExtResponse = buildQueryPersonalInfoExtResponse(personalBase);
                queryPersonalInfoExtResponseList.add(queryPersonalInfoExtResponse);
            }
        }
        Integer pageCount = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
        pageResult.setCurrentPage(currentPage);
        pageResult.setPageCount(pageCount);
        pageResult.setRowCount(count);
        pageResult.setPageSize(pageSize);
        return queryPersonalInfoExtResponseList;
    }


    public BaseApiResponse updatePersonalLevels(PersonalLevelRequest request) {
        for(String personalId : request.getPersonalIds()) {
            personalBaseExtMapper.updateLevelByPersonalId(personalId, request.getPersonalLevel());
        }
        return BaseApiResponse.newSuccess(Boolean.TRUE);
    }

    private QueryPersonalInfoExtResponse buildQueryPersonalInfoExtResponse(PersonalBase personalBase) {
        QueryPersonalInfoExtResponse queryInfo = new QueryPersonalInfoExtResponse();
        queryInfo.setId(personalBase.getId());
        queryInfo.setPersonalId(personalBase.getPersonalId());
        queryInfo.setPhone(personalBase.getPhone());
        queryInfo.setRealName(personalBase.getRealName());
        queryInfo.setOwnerId(personalBase.getOwnerId());
        queryInfo.setOwnerName(personalBase.getOwnerName());
        SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        queryInfo.setUpdateTime(sdf.format(personalBase.getUpdateTime()));
        queryInfo.setPersonalLevel(personalBase.getParentLevel());
        queryInfo.setSex("男");
        if("2".equals(personalBase.getSex())){
            queryInfo.setSex("女");
        }
        queryInfo.setAuthenticationStatus("未激活");
        if("02".equals(personalBase.getAuthenticationStatus())){
            queryInfo.setAuthenticationStatus("已激活");
        }
        QueryPersonalAccountRequest request = new QueryPersonalAccountRequest();
        request.setPersonalId(personalBase.getPersonalId());
        QueryPersonalAccountResponse personalAccountResponse = personalAccountBiz.queryPersonalAcount(request);
        if(personalAccountResponse != null){
            queryInfo.setPointsBalance(personalAccountResponse.getTotalPoint());
        }

        PersonalDistributionRelation personalDistributionRelation = personalDistributionRelationMapper.queryReferrerByPersonalId(personalBase.getPersonalId());
        if(personalDistributionRelation != null){
            queryInfo.setReferrerId(personalDistributionRelation.getParentId());
            queryInfo.setReferrerName(personalDistributionRelation.getParentName());
        }
        return queryInfo;
    }

    public BaseApiResponse queryPersonalDetail(PersonalDetailRequest request) {
        PersonalBase personalBase = personalBaseMapper.queryDetailByPersonalId(request.getPersonalId() );
        PersonalBaseExt personalBaseExt = personalBaseExtMapper.queryExtDetailByPersonalId(request.getPersonalId() );
        PersonalDetailResponse personalDetailResponse = buildPersonalDetailResponse(personalBase, personalBaseExt);
        return BaseApiResponse.newSuccess(personalDetailResponse);
    }

    private PersonalDetailResponse buildPersonalDetailResponse(PersonalBase personalBase, PersonalBaseExt personalBaseExt) {
        PersonalDetailResponse personalDetailResponse = new PersonalDetailResponse();
        personalDetailResponse.setPersonalId(personalBase.getPersonalId());
        personalDetailResponse.setPhone(personalBase.getPhone());
        personalDetailResponse.setRealName(personalBase.getRealName());
        personalDetailResponse.setEmail(personalBaseExt .getEmail());
        personalDetailResponse.setOwnerId(personalBase.getOwnerId());
        personalDetailResponse.setOwnerName(personalBase.getOwnerName());
        personalDetailResponse.setPersonalLevel(personalBaseExt.getPersonalLevel());
        personalDetailResponse.setRemark(personalBase.getRemark());
        String referrerNameTree = queryReferrerNameTree(personalBase.getPersonalId());
        personalDetailResponse.setReferrerNameTree(referrerNameTree);
        personalDetailResponse.setSex("男");
        if("2".equals(personalBase.getSex())){
            personalDetailResponse.setSex("女");
        }
        personalDetailResponse.setAuthenticationStatus("未激活");
        if("02".equals(personalBase.getAuthenticationStatus())){
            personalDetailResponse.setAuthenticationStatus("已激活");
        }
        QueryPersonalAccountRequest request = new QueryPersonalAccountRequest();
        request.setPersonalId(personalBase.getPersonalId());
        QueryPersonalAccountResponse personalAccountResponse = personalAccountBiz.queryPersonalAcount(request);
        if(personalAccountResponse != null){
            personalDetailResponse.setBygonePointsBalance(personalAccountResponse.getHisPoint());
            personalDetailResponse.setCurrentPointsBalance(personalAccountResponse.getPoint());
        }
        CustomerBaseAuth customerBaseAuth = customerBaseAuthMapper.getByPersonalId(personalBase.getPersonalId());
        if(customerBaseAuth != null){
            personalDetailResponse.setCredential(customerBaseAuth.getCredential());
        }
        return personalDetailResponse;
    }

    private String queryReferrerNameTree(String personalId) {
        StringBuffer stringBuffer = new StringBuffer();
        Boolean appendFlag = false;
        List<PersonalDistributionRelation> personalDistributionRelationList = personalDistributionRelationMapper.queryByPersonalId(personalId);
        while (!CollectionUtils.isEmpty(personalDistributionRelationList)){
            PersonalDistributionRelation personalDistributionRelation = personalDistributionRelationList.get(0);
            if(StringUtils.isNotBlank(personalDistributionRelation.getParentName())){
                if(appendFlag){
                    stringBuffer.append("—>");
                }
                stringBuffer.append(personalDistributionRelation.getParentName());
                appendFlag = true;
            }
            personalDistributionRelationList = personalDistributionRelationMapper.queryByPersonalId(personalDistributionRelation.getParentId());
        }
        return stringBuffer.toString();
    }

    public List<PersonalInviteResponse> queryInvitePersonal(PersonalInviteRequest request, PageResult pageResult) {
        Integer pageSize = request.getPageSize();
        Integer currentPage = request.getCurrentPage();
        if(pageSize == null || pageSize.intValue() == 0){
            pageSize = 10;
        }
        if(currentPage == null || currentPage.intValue() == 0){
            currentPage = 1;
        }
        Integer startRow = (currentPage -1) * pageSize;

        Integer count  = personalDistributionRelationMapper.getPageCount(request.getPersonalId());
        List<PersonalDistributionRelation> personalRelationList = personalDistributionRelationMapper.getPageInfos(request.getPersonalId(), startRow, pageSize);
        List<PersonalInviteResponse> personalInviteResponses = new ArrayList<PersonalInviteResponse>();
        if(!CollectionUtils.isEmpty(personalRelationList)){
            for (PersonalDistributionRelation personalRelation :personalRelationList) {
                PersonalInviteResponse personalInviteResponse = buildPersonalInviteResponse(personalRelation);
                personalInviteResponses.add(personalInviteResponse);
            }
        }
        Integer pageCount = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
        pageResult.setCurrentPage(currentPage);
        pageResult.setPageCount(pageCount);
        pageResult.setRowCount(count);
        pageResult.setPageSize(pageSize);
        return personalInviteResponses;

    }

    private PersonalInviteResponse buildPersonalInviteResponse(PersonalDistributionRelation personalRelation) {
        PersonalInviteResponse personalInviteResponse = new PersonalInviteResponse();
        PersonalBase personalBase = personalBaseMapper.queryDetailByPersonalId(personalRelation.getPersonalId() );
        if(personalBase != null){
            personalInviteResponse.setPersonalId(personalBase.getPersonalId());
            personalInviteResponse.setRealName(personalBase.getRealName());
            personalInviteResponse.setPhone(personalBase.getPhone());
            SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            personalInviteResponse.setCreateTime(sdf.format(personalBase.getCreateTime()));
        }
        return personalInviteResponse;
    }

    public BaseApiResponse updatePersonalOwner(PersonalOwnerRequest request) {
        for(String personalId : request.getPersonalIds()) {
            personalBaseMapper.updateOwnerByPersonalId(personalId, request.getOwnerId(), request.getOwnerName());
        }
        return BaseApiResponse.newSuccess(Boolean.TRUE);
    }



    public BaseApiResponse unBindWechat(WechatUnBindRequest request) {
        Integer result = customerBaseAuthMapper.deleteByPersonalId(request.getPersonalId());
        if (result > 0){
            PersonalBase personalBase =  personalBaseMapper.queryDetailByPersonalId(request.getPersonalId());
            if(personalBase != null ){
                personalBase.setAuthenticationStatus("00");
                personalBaseMapper.updateByPersonalId(personalBase);
            }
            return BaseApiResponse.newSuccess(Boolean.TRUE);
        }
        return BaseApiResponse.newFailure(ResponseCode.GJJ_DELETE_ERROR);
    }

    public BaseApiResponse<List<String>> getPersonalLevelList() {
        Map<String, Object> param = new HashMap<>();
        param.put("type", "personal_level");
        BaseApiResponse<List<DictResponse>> result = adminUserServiceClient.getDictByType(param);
        if(!result.getSuccess()){
            return BaseApiResponse.newFailure(result.getCode(), result.getMessage());
        }
        List<DictResponse> dictResponseList = result.getData();
        List<String> respone = new ArrayList<>();
        if(!CollectionUtils.isEmpty(dictResponseList)){
            for (DictResponse dictResponse : dictResponseList ) {
                respone.add(dictResponse.getCode());
            }
        }
        return BaseApiResponse.newSuccess(respone);
    }

    public BaseApiResponse<List<OwnerInfoResponse>> getOwnerList(String userId, String userType, String platformId) {
        AdminUserRequest param = new AdminUserRequest();
        if(!"1".equals(userType)){
            param.setUserId(userId);
        }
        // 5:表示客户经理
        param.setUserType(5);
        param.setPlatformId(platformId);
        BaseApiResponse<List<AdminUserResponse>> result = adminUserServiceClient.getUserList(param);
        if(!result.getSuccess()){
            return BaseApiResponse.newFailure(result.getCode(), result.getMessage());
        }
        List<AdminUserResponse> adminResponseList = result.getData();
        List<OwnerInfoResponse> respone = new ArrayList<>();
        if(!CollectionUtils.isEmpty(adminResponseList)){
            for (AdminUserResponse adminUserResponse : adminResponseList ) {
                OwnerInfoResponse ownerInfoResponse = new OwnerInfoResponse();
                ownerInfoResponse.setOwnerId(adminUserResponse.getUserId());
                ownerInfoResponse.setOwnerName(adminUserResponse.getUsername());
                ownerInfoResponse.setRealName(adminUserResponse.getUsername());
                ownerInfoResponse.setEmail(adminUserResponse.getEmail());
                ownerInfoResponse.setPhone(adminUserResponse.getMobilePhone());
                ownerInfoResponse.setSex(adminUserResponse.getSex());
                respone.add(ownerInfoResponse);
            }
        }
        return BaseApiResponse.newSuccess(respone);
    }

    public BaseApiResponse addPersonalPoints(PersonalPointsRequest request) {
        CustomerBase customerBase = new CustomerBase();
        customerBase.setPlatformId(request.getPlatformId());
        customerBase.setPersonalId(request.getPersonalId());
        customerBase = customerBaseMapper.selectOne(customerBase);
        if(customerBase == null){
            return BaseApiResponse.newFailure(ResponseCode.ACC_ERROR);
        }
        IntoAccountRequest intoAccountRequest = new IntoAccountRequest();
        intoAccountRequest.setPersonalId(request.getPersonalId());
        intoAccountRequest.setPlatformId(request.getPlatformId());
        intoAccountRequest.setCustomerId(customerBase.getCustomerId());
        intoAccountRequest.setAccountType(AccountType.ACC_INTEGRAL.getCode());
        intoAccountRequest.setCustomerType(CustomerType.CUST_PERSONAL.getCode());
        intoAccountRequest.setIntoAccAmt(String.valueOf(request.getPoints()));
        intoAccountRequest.setOrderNo(String.valueOf(SnowFlake.getId()));

        if(1 == request.getPointsType()){
            // 业务奖励积分
            intoAccountRequest.setTradeType(PointsTradeType.POINTS_BIZ.getCode());
        } else if(2 == request.getPointsType()){
            //推荐奖励积分
            intoAccountRequest.setTradeType(PointsTradeType.POINTS_RECOMMEND.getCode());
        } else {
            // 默认：积分冲抵
            intoAccountRequest.setTradeType(PointsTradeType.POINTS_DEDUCTION.getCode());
        }
        intoAccountRequest.setTxFee("0");
        intoAccountRequest.setAccountName(AccountType.ACC_INTEGRAL.getDesc());
        customerIntoAccountBiz.intoAccount(intoAccountRequest);
        return BaseApiResponse.newSuccess(Boolean.TRUE);
    }

//
//    public BaseApiResponse modifyPersonal(PersonalBaseModifyRequest request, String customerId, String customerName) {
//        PersonalBase personalBase = personalBaseMapper.queryDetailByPersonalId(request.getPersonalId());
//        Date nowDate =  new Date();
//        if(personalBase != null){
//            personalBase.setRealName(request.getRealName());
//            personalBase.setSex(request.getSex());
//            personalBase.setPhone(request.getPhone());
//            personalBase.setRemark(request.getRemark());
//            personalBase.setUpdateTime(nowDate);
//            personalBaseMapper.updateByPrimaryKey(personalBase);
//        }
//        PersonalBaseExt personalBaseExt = personalBaseExtMapper.queryExtDetailByPersonalId(request.getPersonalId());
//        if(personalBaseExt != null){
//            personalBaseExt.setUpdateTime(nowDate);
//            personalBaseExt.setEmail(request.getEmail());
//            personalBaseExt.setPersonalLevel(request.getPersonalLevel());
//            personalBaseExtMapper.updateByPrimaryKey(personalBaseExt);
//        }
//        return BaseApiResponse.newSuccess(Boolean.TRUE);
//    }

}